const express = require('express');
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');
const authMiddleware = require('../middleware/auth');

// 管理员登录页面
router.get('/login', (req, res) => {
  res.render('admin/login');
});

// 管理员登录处理
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const user = await User.findOne({ username });
    
    if (!user || user.role !== 'admin') {
      return res.status(401).send('无效的管理员凭证');
    }
    
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return res.status(401).send('无效的管理员凭证');
    }
    
    req.session.user = user;
    res.redirect('/admin/dashboard');
  } catch (err) {
    console.error(err);
    res.status(500).send('服务器错误');
  }
});

// 管理员仪表盘
router.get('/dashboard', authMiddleware.adminRequired, (req, res) => {
  res.render('admin/dashboard');
});

// 用户管理
router.get('/users', authMiddleware.adminRequired, async (req, res) => {
  try {
    const users = await User.find({});
    res.render('admin/users', { users });
  } catch (err) {
    console.error(err);
    res.status(500).send('服务器错误');
  }
});

// 媒体文件上传
router.post('/upload', authMiddleware.adminRequired, async (req, res) => {
  try {
    if (!req.files || Object.keys(req.files).length === 0) {
      return res.status(400).send('未上传任何文件');
    }
    
    const mediaFile = req.files.media;
    const allowedTypes = ['image/jpeg', 'image/png', 'video/mp4'];
    const maxSize = 10 * 1024 * 1024; // 10MB
    
    if (!allowedTypes.includes(mediaFile.mimetype)) {
      return res.status(400).send('不支持的文件类型');
    }
    
    if (mediaFile.size > maxSize) {
      return res.status(400).send('文件大小超过限制');
    }
    
    const uploadPath = path.join(__dirname, '../public/medias', mediaFile.name);
    
    await mediaFile.mv(uploadPath);
    
    // 保存到数据库
    const newMedia = new MediaFile({
      name: mediaFile.name,
      path: `/medias/${mediaFile.name}`,
      size: mediaFile.size,
      type: mediaFile.mimetype
    });
    
    await newMedia.save();
    
    res.send('文件上传成功');
  } catch (err) {
    console.error(err);
    res.status(500).send('文件上传失败');
  }
});

module.exports = router;